import { encrypt, decrypt } from "./aes.js";
class StorageModel {
  /**
   * name
   */
  constructor(type) {
    this.type = type || "localStorage";
  }
  get(name) {
    if (this.type === "localStorage") {
      const data = localStorage.getItem(name) || "";
      let newData;
      try {
        const calcData = JSON.parse(
          process.env.NODE_ENV === "development" ? data : decrypt(data)
        );
        if (Array.isArray(calcData)) {
          newData = [...calcData];
        } else if (calcData instanceof Object) {
          newData = { ...calcData };
        } else {
          newData =
            process.env.NODE_ENV === "development" ? data : decrypt(data);
        }
      } catch (error) {
        newData = process.env.NODE_ENV === "development" ? data : decrypt(data);
      }
      return newData;
    } else {
      const data = sessionStorage.getItem(name) || "";
      var newData;
      try {
        const calcData = JSON.parse(
          process.env.NODE_ENV === "development" ? data : decrypt(data)
        );
        if (Array.isArray(calcData)) {
          newData = [...calcData];
        } else if (calcData instanceof Object) {
          newData = { ...calcData };
        } else {
          newData =
            process.env.NODE_ENV === "development" ? data : decrypt(data);
        }
      } catch (error) {
        newData = process.env.NODE_ENV === "development" ? data : decrypt(data);
      }
      return newData;
    }
  }
  set(name, data) {
    let newData;
    if (typeof data === "string") {
      newData = data || "";
    } else if (typeof data === "object") {
      newData = JSON.stringify(data) || "";
    } else {
      newData = data;
    }
    if (this.type === "localStorage") {
      return localStorage.setItem(
        name,
        process.env.NODE_ENV === "development" ? newData : encrypt(newData)
      );
    } else {
      return sessionStorage.setItem(
        name,
        process.env.NODE_ENV === "development" ? newData : encrypt(newData)
      );
    }
  }
  remove(name) {
    if (this.type === "localStorage") {
      return localStorage.removeItem(name);
    } else {
      return sessionStorage.removeItem(name);
    }
  }
  clear() {
    if (this.type === "localStorage") {
      localStorage.clear();
    } else {
      sessionStorage.clear();
    }
  }
}

export const Storage = new StorageModel();
export const SeStorage = new StorageModel('sessionStorage');
